//
//  NSString+Cool.m
//  HX2Car
//
//  Created by Mudmen on 16/7/20.
//  Copyright © 2016年 Hx2car_mac. All rights reserved.
//

#import "NSString+Cool.h"
//#import "SZGlobal.h"
@implementation NSString (Cool)

+ (NSString*)weekDayStr:(NSString *)format
{
    NSString *weekDayStr = nil;
    NSDateComponents *comps = [[NSDateComponents alloc] init];
    
    NSString *str = format;
    if (str.length >= 10) {
        NSString *nowString = [str substringToIndex:10];
        NSArray *array = [nowString componentsSeparatedByString:@"-"];
        if (array.count == 0) {
            array = [nowString componentsSeparatedByString:@"/"];
        }
        if (array.count >= 3) {
            NSInteger year = [[array objectAtIndex:0] integerValue];
            NSInteger month = [[array objectAtIndex:1] integerValue];
            NSInteger day = [[array objectAtIndex:2] integerValue];
            [comps setYear:year];
            [comps setMonth:month];
            [comps setDay:day];
        }
    }
    
    NSCalendar *gregorian = [[NSCalendar alloc]
                             initWithCalendarIdentifier:NSCalendarIdentifierGregorian];
    NSDate *_date = [gregorian dateFromComponents:comps];
    NSDateComponents *weekdayComponents = [gregorian components:NSCalendarUnitWeekday fromDate:_date];
    NSInteger week = [weekdayComponents weekday];
    
    switch (week) {
        case 1:
            weekDayStr = @"星期日";
            break;
        case 2:
            weekDayStr = @"星期一";
            break;
        case 3:
            weekDayStr = @"星期二";
            break;
        case 4:
            weekDayStr = @"星期三";
            break;
        case 5:
            weekDayStr = @"星期四";
            break;
        case 6:
            weekDayStr = @"星期五";
            break;
        case 7:
            weekDayStr = @"星期六";
            break;
        default:
            weekDayStr = @"";
            break;
    }
    return weekDayStr;
}

+ (NSString *)getNowTimeTimestamp
{
    NSDate *datenow = [NSDate date];//现在时间,你可以输出来看下是什么格式
    NSString *timeSp = [NSString stringWithFormat:@"%ld", (long)([datenow timeIntervalSince1970]*1000)];
    return timeSp;
}

- (NSDictionary *)jsonToDictionary
{
    NSDictionary *dicts = [NSJSONSerialization JSONObjectWithData:[self dataUsingEncoding:NSUTF8StringEncoding] options:NSJSONReadingMutableContainers error:nil];
    return dicts;
}

- (NSArray *)jsonToArray {
    NSArray  *array = [NSJSONSerialization JSONObjectWithData:[self dataUsingEncoding:NSUTF8StringEncoding] options:NSJSONReadingMutableContainers error:nil];
    return array;
}

// 时间戳转换时间
+ (NSString *)timeSwitchStr:(NSString *)timeChuo
{
    NSInteger time= [timeChuo integerValue] / 1000;
    NSDate *detaildate=[NSDate dateWithTimeIntervalSince1970:time];
    //实例化NSDateFormatter对象
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    //设定时间格式
    [dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
    NSString *timeStr = [dateFormatter stringFromDate: detaildate];
    return timeStr;
}

// 时间戳转换时间
+ (NSString *)timeyymddStr:(NSString *)timeChuo
{
    NSInteger time= [timeChuo integerValue] / 1000;
    NSDate *detaildate=[NSDate dateWithTimeIntervalSince1970:time];
    //实例化NSDateFormatter对象
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    //设定时间格式
    [dateFormatter setDateFormat:@"yyyy-MM-dd"];
    NSString *timeStr = [dateFormatter stringFromDate: detaildate];
    return timeStr;
}


// 时间戳转换时间
+ (NSString *)timeMMDDStr:(NSString *)timeChuo
{
    NSInteger time= [timeChuo integerValue] / 1000;
    NSDate *detaildate=[NSDate dateWithTimeIntervalSince1970:time];
    //实例化NSDateFormatter对象
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    //设定时间格式
    [dateFormatter setDateFormat:@"MM-dd"];
    NSString *timeStr = [dateFormatter stringFromDate: detaildate];
    return timeStr;
}

+ (NSString *)stringFromDate:(NSDate *)date{
    
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    
    
    
    //zzz表示时区，zzz可以删除，这样返回的日期字符将不包含时区信息。
    
    [dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
    
    
    
    NSString *destDateString = [dateFormatter stringFromDate:date];
    
    
    return destDateString;
}

- (NSString*)UFT8Nst{
  return   [self stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet  URLQueryAllowedCharacterSet]];
}

+ (NSString *)formatString:(NSString *)formatString WithString:(NSString *)string
{
    if (!formatString) {
        return formatString;
    }
    if ([formatString isKindOfClass:[NSNull class]]) {
        return nil;
    }
    NSRange range = [formatString rangeOfString:@"http"];
    if (range.location == NSNotFound) {
        formatString = [NSString stringWithFormat:@"%@%@",string,formatString];
    }
    return formatString;
}

+ (NSString *)firstPicFormatString:(NSString *)formatString WithString:(NSString *)string
{
    if (!formatString) {
        return formatString;
    }
    if ([formatString isKindOfClass:[NSNull class]]) {
        return nil;
    }
    NSArray *pic = [formatString componentsSeparatedByString:@","];
    NSString *firstPic = pic[0];
    if (firstPic.length == 0) {
        return nil;
    }
    NSRange range = [firstPic rangeOfString:@"http"];
    if (range.location == NSNotFound) {
        formatString = [NSString stringWithFormat:@"%@%@",string,firstPic];
    }
    return formatString;
}

- (CGSize)sizeWithString:(NSString *)string font:(UIFont *)font constraintSize:(CGSize)constraintSize
{
    CGSize stringSize = CGSizeZero;
    
    NSDictionary *attributes = @{NSFontAttributeName:font};
    NSInteger options = NSStringDrawingUsesFontLeading | NSStringDrawingTruncatesLastVisibleLine | NSStringDrawingUsesLineFragmentOrigin;
    CGRect stringRect = [string boundingRectWithSize:constraintSize options:options attributes:attributes context:NULL];
    stringSize = stringRect.size;
    
    return stringSize;
}

+ (NSString *)reviseString:(NSString *)string
{
    
    if (!string || [string isKindOfClass:[NSNull class]]) {
        return nil;
    }
    /* 直接传入精度丢失有问题的Double类型*/
    double conversionValue        = (double)[string floatValue];
    NSString *doubleString        = [NSString stringWithFormat:@"%lf", conversionValue];
    NSDecimalNumber *decNumber    = [NSDecimalNumber decimalNumberWithString:doubleString];
    return [decNumber stringValue];
}
- (UIImage*)creatErWeiMaImageWithPicWidth:(CGFloat)width{
    //  1. 创建一个二维码滤镜实例(CIFilter)
    CIFilter *filter = [CIFilter filterWithName:@"CIQRCodeGenerator"];
    // 滤镜恢复默认设置
    [filter setDefaults];
    
    // 2. 给滤镜添加数据
    
    NSData *data = [self dataUsingEncoding:NSUTF8StringEncoding];
    
    [filter setValue:data forKeyPath:@"inputMessage"];
    
    // 3. 生成二维码
    CIImage *image = [filter outputImage];
    //    4. 显示二维码
    return [self createNonInterpolatedUIImageFormCIImage:image withSize:width];
}

- (UIImage *)createNonInterpolatedUIImageFormCIImage:(CIImage *)image withSize:(CGFloat) size {
    
    CGRect extent = CGRectIntegral(image.extent);
    CGFloat scale = MIN(size/CGRectGetWidth(extent), size/CGRectGetHeight(extent));
    
    // 1.创建bitmap;
    size_t width = CGRectGetWidth(extent) * scale;
    size_t height = CGRectGetHeight(extent) * scale;
    CGContextRef bitmapRef = CGBitmapContextCreate(nil, width, height, 8, 0, CGColorSpaceCreateDeviceGray(), (CGBitmapInfo)kCGImageAlphaNone);
    CIContext *context = [CIContext contextWithOptions:nil];
    CGImageRef bitmapImage = [context createCGImage:image fromRect:extent];
    CGContextSetInterpolationQuality(bitmapRef, kCGInterpolationNone);
    CGContextScaleCTM(bitmapRef, scale, scale);
    CGContextDrawImage(bitmapRef, extent, bitmapImage);
    
    // 2.保存bitmap到图片
    CGImageRef scaledImage = CGBitmapContextCreateImage(bitmapRef);
    CGContextRelease(bitmapRef);
    CGImageRelease(bitmapImage);
    return [UIImage imageWithCGImage:scaledImage];
}

- (NSAttributedString *)addPicToNum:(NSInteger)num pic:(NSString*)pic picFrame:(CGRect)frame{
    //创建富文本
    NSMutableAttributedString *attri = [[NSMutableAttributedString alloc] initWithString:self];
    //NSTextAttachment可以将要插入的图片作为特殊字符处理
    NSTextAttachment *attch = [[NSTextAttachment alloc] init];
    //定义图片内容及位置和大小
    attch.image = [UIImage imageNamed:pic];
    attch.bounds = frame;
    //创建带有图片的富文本
    NSAttributedString *string = [NSAttributedString attributedStringWithAttachment:attch];
    
    
    //将图片放在最后一位
    if (num == self.length) {
        [attri appendAttributedString:string];
    }else{
        //将图片放在第一位
        [attri insertAttributedString:string atIndex:num];
    }
    //用label的attributedText属性来使用富文本
    return attri;
    

}

@end
